package com.service.lotterySystem.config;

import com.service.config.annotation.Log;
import com.service.config.enums.BusinessStatus;
import com.service.config.utils.IdUtil;
import com.service.config.utils.JsonXMLUtils;
import com.service.config.utils.RedisUtil;
import com.service.lotterySystem.dao.VLogOperateDao;
import com.service.lotterySystem.entity.VLogOperate;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;


/**
 * 操作日志记录处理
 *
 * @ClassName OperLogAspect
 * @Description TODO
 * @Author mmc
 * @Date 2019-10-23 17:36
 * @Version 1.0
 **/
@Aspect
@Slf4j
@Component
public class OperLogAspect {

    @Resource
    private VLogOperateDao logOperateMapper;

    @Pointcut("@annotation(com.service.config.annotation.Log)")
    public void logPointCut() {
    }


    @AfterReturning(pointcut = "logPointCut()")
    public void doAfterReturning(JoinPoint joinPoint) {
        handleLog(joinPoint, null, BusinessStatus.SUCCESS.ordinal());
    }


    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, BusinessStatus.FAIL.ordinal());
    }

    private void handleLog(final JoinPoint joinPoint, final Exception e, int status) {
        try {
            // 获得注解
            Log controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }
            // 接收到请求，记录请求内容
//            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//            // 从获取RequestAttributes中获取HttpServletRequest的信息
//            assert requestAttributes != null;
//            HttpServletRequest request = requestAttributes.getRequest();
            // *========数据库日志=========*//
            VLogOperate logOperate = new VLogOperate();
            logOperate.setId(IdUtil.getStringId());
            logOperate.setBusinesstype(controllerLog.businessType().name());// 操作类型
            logOperate.setOperation(controllerLog.operatorType().name());// 操作人类别
            logOperate.setOperTime(new Date());
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            logOperate.setStatus(status);
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            logOperate.setMethod(className + "." + methodName + "()");
            if (BusinessStatus.FAIL.ordinal() == status) {
                logOperate.setErrMsg(e.getMessage());
            }
            // 请求的方法参数值
            Object[] args = joinPoint.getArgs();
            LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
            // 请求的参数
            String[] paramNames = u.getParameterNames(method);
            if (args != null && paramNames != null) {
                StringBuilder params = new StringBuilder(); // 线程不安全的String类
                for (int i = 0; i < args.length; i++) {
                    if (args[i] instanceof HttpServletRequest) {
                        params.append(" ");
                    }else {
                        params.append(paramNames[i]).append(":").append(args[i]).append(" ");
                    }
                }
                logOperate.setArgs(JsonXMLUtils.obj2json(Arrays.stream(args).toArray()));
            }
            logOperateMapper.insert(logOperate);
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }
}
